package com.wjh.controller;

import com.wjh.bean.Constants;
import com.wjh.bean.Result;
import com.wjh.feign.PayCallBackServiceFeign;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Author: 王金海
 * @Description: 支付回调
 * @Date: Created by Administrator on 2018/6/27.
 * @Modified By:
 */
@Controller
@RequestMapping("callBack")
@Slf4j
public class PayCallBackController {

    public static String PAYSUCCESS="pay_success";
    public static String ERROR="error";

    @Value("${synSuccessPage_url}")
    public String synSuccessPageUrl;
    @Autowired
    private PayCallBackServiceFeign payCallBackServiceFeign;

    /**
     * 同步回调
     * @param request
     * @return
     * @throws UnsupportedEncodingException
     */
    @RequestMapping("synCallBack")
    public void synCallBack(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();

        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        Result result = payCallBackServiceFeign.synCallBack(params);
        if (result.getCode()!= Constants.HTTP_RES_CODE_200) {
            request.setAttribute("error",result.getMsg());
            return;
        }
        LinkedHashMap data=(LinkedHashMap) result.getData();
        //商户订单号
        String out_trade_no = (String) data.get("out_trade_no");
        //支付宝交易号
        String trade_no = (String) data.get("trade_no");
        //付款金额
        String total_amount = (String) data.get("total_amount");

        String htmlFrom = "<form name='punchout_form'"
                + " method='post' action='"+synSuccessPageUrl+"' >"
                + "<input type='hidden' name='outTradeNo' value='" + out_trade_no + "'>"
                + "<input type='hidden' name='tradeNo' value='" + trade_no + "'>"
                + "<input type='hidden' name='totalAmount' value='" + total_amount + "'>"
                + "<input type='submit' value='立即支付' style='display:none'>"
                + "</form><script>document.forms[0].submit();" + "</script>";
        writer.println(htmlFrom);
        writer.close();
    }


    /**
     * 隐藏参数重定向
     * @param request
     * @param outTradeNo
     * @param tradeNo
     * @param totalAmount
     * @return
     */
    @PostMapping("synSuccessPage")
    public String synSuccessPage(HttpServletRequest request, String outTradeNo, String tradeNo, String totalAmount) {
        request.setAttribute("outTradeNo", outTradeNo);
        request.setAttribute("tradeNo", tradeNo);
        request.setAttribute("totalAmount", totalAmount);
        return PAYSUCCESS;
    }

    /**
     * 异步回调
     * @return
     */
    @RequestMapping("asynCallBack")
    public String asynCallBack(HttpServletRequest request) {
        log.warn("----------------异步回调开始---------------");
        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
//            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        String callBack = payCallBackServiceFeign.asynCallBack(params);
        log.warn("----------------异步回调结束---------------");
        return callBack;
    }
}
